package cn.nawang.ebeim.test.db;

import cn.nawang.ebeim.test.constants.InitSql;
import cn.nawang.ebeim.test.domain.FileInfo;
import cn.nawang.ebeim.test.domain.Root;
import cn.nawang.ebeim.test.handler.BeanListHandler;
import cn.nawang.ebeim.test.utils.DBPool;
import cn.nawang.ebeim.test.utils.DBUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by GanJc on 2015-12-08 14:22
 */
public class DBHelper {

    private String url = "jdbc:sqlite:test.db";

    public void initDB() throws SQLException {
        DBUtils.execute(getConnection(), InitSql.CREATE_ROOT_TABLE, null);
        DBUtils.execute(getConnection(), InitSql.CREATE_FILE_TABLE, null);
    }

    public void saveRoot(Root root) throws SQLException {
        String sql = "insert into root(root_path,abs_path,total_dir,total_file) values(?,?,?,?)";
        Object[] params = {root.getRootPath(),root.getAbsPath(),root.getTotalDir(),root.getTotalFile()};
        DBUtils.execute(getConnection(), sql, params);
    }

    public void saveFile(FileInfo fileInfo) throws SQLException {
        String sql = "insert into file_info(container,signature,file_path,root_path,abs_path) values(?,?,?,?,?)";
        Object[] params = {fileInfo.getContainer(),fileInfo.getSignature(),fileInfo.getFilePath(), fileInfo.getRootPath(), fileInfo.getAbsPath()};
        DBUtils.execute(getConnection(), sql, params);
    }

    public void saveFiles(List<FileInfo> files) throws SQLException {
        String sql = "insert into file_info(file_path,root_path,abs_path) values(?,?,?)";
        DBUtils.executeBatch(getConnection(), sql, files);
    }

    public List<FileInfo> findFiles(){
        List list = null;
        String sql = "select * from file_info ";
        BeanListHandler rsh = new BeanListHandler(FileInfo.class);
        try {
            list = (List) DBUtils.find(getConnection(),sql, null, rsh);
        } catch (Exception e) {
            System.out.println("读取数据库异常,异常信息:"+e.getMessage());
        }
        return list;
    }

    public Connection getConnection() {
        return  DBPool.getInstance().getConnection(url, "", "");
    }

}
